import axios from 'axios';
import { Message } from '@alifd/next';
import { history } from '../index';
import addr from '../apiConfig';

const authApi = `${addr}token`;
function auth() {
  const type = sessionStorage.getItem('auth.type', '');
  const accessToken = sessionStorage.getItem('auth.accessToken', '');
  const refreshToken = sessionStorage.getItem('auth.refreshToken', '');
  return {
    type: type,
    accessToken: accessToken,
    refreshToken: refreshToken,
  };
}
function logout() {
  const type = sessionStorage.getItem('auth.type', '');
  if (type === 'jwt') {
    sessionStorage.removeItem('auth.type');
    sessionStorage.removeItem('auth.accessToken');
    sessionStorage.removeItem('auth.refreshToken');
  }
}
let temp = { type: undefined, accessToken: undefined };
function setAuth(data) {
  temp = data;
  sessionStorage.setItem('auth.type', data.type);
  sessionStorage.setItem('auth.refreshToken', data.refreshToken);
  sessionStorage.setItem('auth.accessToken', data.accessToken);
}
function refreshAuth(data) {
  temp.accessToken = data;
  sessionStorage.setItem('auth.accessToken', data);
}

axios.interceptors.request.use(config => {
  if (temp.type === undefined) {
    temp = auth();
  }
  config.headers = {
    'Access-Control-Allow-Origin': '*',
  };
  if (temp.type === 'jwt') {
    config.headers.auth = temp.accessToken;
  }
  return config;
});
axios.interceptors.response.use(
  response => {
    if (response.data.code === 500) {
      Message.warning(response.data.msg);
    }
    return response;
  },
  error => {
    if (error === undefined || error.code === 'ECONNABORTED') {
      Message.error('服务请求超时');
      return Promise.reject(error);
    }
    const { response: { status } } = error;
    if (status === 405) {
      if (auth().type === 'normal') {
        Message.warning('未登录或登录超时!');
        if (history.location.pathname.indexOf('/user/login') === -1) {
          history.push('/user/login');
        }
      } else {
        const config = error.config;
        const backoff = new Promise( (resolve) => {
          axios.post(authApi, {
            token: auth().refreshToken,
          }).then(response => {
            if (response.data.code === 200) {
              refreshAuth(response.data.data);
              resolve();
            } else {
              Message.warning('未登录或登录超时!');
              if (history.location.pathname.indexOf('/user/login') === -1) {
                history.push('/user/login');
              }
            }
          });
        });
        return backoff.then(() => {
          return axios(config);
        });
      }
    }
    if (status === 403) {
      Message.warning('暂无权限!');
    }
    if (status === 502) {
      Message.warning('服务器无响应...');
    }

    if (status === 500) {
      Message.warning('服务器错误');
    }

    return Promise.reject(error);
  }
);

// const paxios = axios;
export { axios, setAuth, auth, logout };
